package com.lq.pc.webmagic;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

public class CSDNBlogProcessor implements PageProcessor {

    public static final String URL_LIST = "https://blog.csdn.net/\\w*/article/details/\\d{8}";
    public static final String START_URL = "^https://blog.csdn.net$";
    public static final String AJAX = "https://blog.csdn.net/api/articles?type=more&category=home&shown_offset=15358150\\d{8}";

    private Site site = Site
            .me()
            .setDomain("blog.sina.com.cn")
            .setSleepTime(11)
            .setUserAgent(
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
    int i = 0;

    @Override
    public void process(Page page) {
        if (page.getUrl().regex(START_URL).match()) {
            System.out.println("  url-->" + (++i) + page.getUrl().toString());
            List<String> all = page.getHtml().xpath("//ul[@class='feedlist_mod home']/li").links().regex(URL_LIST).all();
            page.addTargetRequests(all);
        } else if (page.getUrl().regex(URL_LIST).match()) {
            page.putField("title", page.getHtml().xpath("//h1[@class='title-article']/text()"));
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new CSDNBlogProcessor()).addUrl("https://blog.csdn.net")
                .run();

    }
}